package besta.moon.sql.expression.function.numeric;

import besta.moon.sql.expression.function.FunctionReturnP1Number;
import besta.moon.sql.parser.SQLTokenizer;

public final class FunctionRound extends FunctionReturnP1Number {

    @Override
    public final int getFunction() {
        return SQLTokenizer.ROUND;
    }

    @Override
    public boolean isNull() throws Exception {
        return param1.isNull() || param2.isNull();
    }

    @Override
    public final double getDouble() throws Exception {
        if (isNull()) {
            return 0;
        }
        final int places = param2.getInt();
        double value = param1.getDouble();
        long factor = 1;
        if (places > 0) {
            for (int i = 0; i < places; i++) {
                factor *= 10;
            }
            value *= factor;
        } else {
            for (int i = 0; i > places; i--) {
                factor *= 10;
            }
            value /= factor;
        }
        value = Math.rint(value);
        if (places > 0) {
            value /= factor;
        } else {
            value *= factor;
        }
        return value;
    }

}
